home *** CD-ROM | disk | FTP | other *** search
- /* ipname.c
- *
- * portable across unix/ultrix & vms systems
- * first version (90/06/20) by Daniel Karrenberg (dfk@cwi.nl)
- * this version (91/07/10) by Davide Salomoni (salomoni@cnaf.infn.it)
- * to be linked on VMS systems with the appropriate socket library.
- * Usage: ipname [secs]
- * [secs] are the max seconds to wait for the gethostbyname() function
- * to return (default=DEFSEC).
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <netdb.h>
- #include <signal.h>
- #include <setjmp.h>
-
- #ifdef VAXC
- #include <socket.h>
- #include <in.h>
- #else
- #include <sys/socket.h>
- #include <netinet/in.h>
- #endif
-
- #define CACHE 50 /* dimension of the cyclic cache (don't exaggerate!) */
- #define DEFSEC 15 /* max seconds to wait for gethostbyname() to return */
-
- char *giveme(char *string);
- int timeout();
-
- unsigned sec=0;
- jmp_buf env;
-
- struct entry {
- int addr;
- char name[40];
- };
- static struct entry *p[CACHE];
-
- main(int argc, char **argv)
- {
- char l[81],from[40],to[40];
- unsigned int packets,bytes;
-
- if (argc>1) sec=atoi(argv[1]);
- if (!sec) sec=DEFSEC;
- signal(SIGALRM,timeout);
-
- while (fgets(l, sizeof(l), stdin) != NULL) {
- if (isdigit(l[0])) {
- sscanf(l, "%s %s %d %d\n", from, to, &packets, &bytes);
- printf("%-29.29s %-29.29s%8d%10d K\n",
- giveme(from), giveme(to), packets, bytes/1024);
- }
- else
- fputs(l, stdout);
- }
- exit(0);
- }
-
-
- char *giveme(char *string)
- {
- struct in_addr ha;
- struct hostent *h;
- register int j;
- static int i=0,max=0;
- int l;
-
- ha.s_addr=inet_addr(string);
- for (j=0;j<max;j++)
- if (ha.s_addr==p[j]->addr)
- return(strcpy(string,p[j]->name)); /* cache hit */
-
- /* cache miss */
- if (p[i]==NULL)
- if ((p[i]=(struct entry *)malloc(sizeof(struct entry)))==NULL) {
- fprintf(stderr,"ipname: memory allocation error\n");
- exit(1);
- }
- p[i]->addr=ha.s_addr;
-
- alarm(sec);
- if (!setjmp(env) && (h=gethostbyaddr(&ha, 4, AF_INET))!=NULL) {
- l=strlen(h->h_name);
- strcpy(p[i]->name,l>29?h->h_name+(l-29):h->h_name);
- strcpy(string,p[i]->name);
- } else strcpy(p[i]->name,string);
- alarm(0);
-
- i = ++i % CACHE;
- if (max<CACHE) max++;
- return(string);
- }
-
-
- int timeout()
- {
- alarm(0);
- longjmp(env,1);
- }
-